package com.wisdom.smartbook.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.media.ExifInterface;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import androidx.camera.core.ImageProxy;

import com.google.mlkit.vision.face.Face;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;

/**
 * @ClassName: BitmapUtils
 * @Description: java类作用描述
 * @Author: xjliu
 * @CreateDate: 2024/3/13 4:26 下午
 * @Version: 1.0
 */

public class BitmapUtils {
    public static Bitmap imageToBitmap(ImageProxy imageProxy) {
        ByteBuffer yBuffer = imageProxy.getPlanes()[0].getBuffer();// Y
        ByteBuffer vuBuffer = imageProxy.getPlanes()[2].getBuffer(); // VU
        int ySize = yBuffer.remaining();
        int vuSize = vuBuffer.remaining();
        byte[] nv21 = new byte[ySize + vuSize];
        yBuffer.get(nv21, 0, ySize);
        vuBuffer.get(nv21, ySize, vuSize);
        YuvImage yuvImage = new YuvImage(nv21, ImageFormat.NV21, imageProxy.getWidth(), imageProxy.getHeight(), null);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        yuvImage.compressToJpeg(new Rect(0, 0, yuvImage.getWidth(), yuvImage.getHeight()), 40, out);
        byte[] imageBytes = out.toByteArray();
        return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
    }

    /**
     * 为人脸绘制边框
     *
     * @param bitmap
     * @param face   采集的人脸
     * @return {@link Bitmap}
     */
    public static Bitmap drawWithRectangle(Bitmap bitmap, Face face) {

        //复制一个新的Bitmap
        Bitmap copiedBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());

//        for (Face face : faces) {
        //获取边界状态
        // 初始化Paint
        Paint paint = new Paint();
        // 设置矩形颜色
        paint.setColor(Color.GREEN);
        // 设置绘制样式为轮廓绘制
        paint.setStyle(Paint.Style.STROKE);
        // 设置为你需要的宽度
        paint.setStrokeWidth(10);

        Canvas canvas = new Canvas(copiedBitmap);
        canvas.drawRect(face.getBoundingBox(), paint);
//        }
        return copiedBitmap;
    }


    /**
     * 读取图片属性：旋转的角度
     *
     * @param path 图片绝对路径
     * @return degree旋转的角度
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /*
     * 旋转图片
     * @param angle
     * @param bitmap
     * @return Bitmap
     */
    public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
        //旋转图片 动作
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        // 创建新的图片
        Bitmap bitmap1 = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
//        ivPhoto.setImageBitmap(bitmap1); // 展示刚拍过的照片
        return bitmap1;
    }

    public static void saveBitmapFileToFile(Context context, Bitmap bitmap, String imageFilePath) {
        File filemm = new File(imageFilePath); //
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filemm));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //说明第一个参数上下文，第二个参数是文件路径例如：/storage/emulated/0/1621832516463_1181875151.mp4 第三个参数是文件类型，传空代表自行根据文件后缀判断刷新到相册
        MediaScannerConnection.scanFile(context, new String[]{imageFilePath}, null, new MediaScannerConnection.OnScanCompletedListener() {
            @Override
            public void onScanCompleted(String path, Uri uri) {
                //刷新成功的回调方法
                Log.e("资源刷新成功路径为", path);
            }
        });
    }

    /**
     * 裁剪图片
     * @param originalImage
     * @param srcRect
     * @return
     */
    public static Bitmap clipBitmap(Bitmap originalImage, Rect srcRect) {
        // 创建新的空白画布对象
        int width = srcRect.width();
        int height = srcRect.height();
        // 创建新的画布大小为550X452位图对象
        Bitmap croppedImage = Bitmap.createBitmap(width, height, originalImage.getConfig());
        // 创建画布并将其与新的位图关联起来
        Canvas canvas = new Canvas(croppedImage);
        canvas.drawARGB(0, 0, 0, 0); // 设置画布透明度为完全不透明（默认值）
        // 目标矩形区域
        Rect destRect = new Rect(0, 0, width, height);
        // 调用 drawBitmap() 函数进行剪切操作
        canvas.drawBitmap(originalImage, srcRect, destRect, null);
        // 显示或保存剪切后的图片
        return croppedImage;
    }
}